<template>
    <div>
        <!-- 面包屑导航 separator以>分割 -->
        <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 面板 一个方形区域 -->
        <el-card class="box-card">
            <!-- 每个row  gutter="24"是24列  -- col :span="12" 占12
                一个占12 其实就是一半50%
            -->
            <!-- 按钮和文本框 -->
            <el-row :gutter="24">
                <el-col :span="12">
                    <div class="grid-content bg-purple">
                        <!--  clearable 显示x @clear 点击x触发事件 -->
                        <el-input
                            v-model="queryinfo.query"
                            clearable
                            @clear="getuserlist"
                            placeholder="请输入内容"
                            class="input-with-select"
                        >
                            <el-button @click="getuserlist" slot="append" icon="el-icon-search"></el-button>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="grid-content bg-purple-light">
                        <el-button @click="dialogVisible=true" type="primary">添加用户</el-button>
                    </div>
                </el-col>
            </el-row>
            <!-- 表格 :data="ajax拿到的数组"  prop就是数据名字  label 表头 -->
            <!-- 如果只显示字 就直接写就行 要在这里面再显示 其他组件或者标签 就要template配合 -->
            <!-- scope.row 一定是当前这行的数据 -->
            <el-table :data="userlist" border="" style="width: 100%">
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名" width="120"></el-table-column>
                <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
                <el-table-column prop="mobile" label="电话" width="120"></el-table-column>
                <el-table-column prop="role_name" label="角色" width="300"></el-table-column>
                <el-table-column prop="mg_state" label="状态" width="120">
                    <template slot-scope="scope">
                        <el-switch @change="changeSwitch(scope.row)" v-model="scope.row.mg_state"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" content="编辑" placement="top">
                            <el-button
                                @click="showEditUser(scope.row.id)"
                                type="primary"
                                size="small"
                                icon="el-icon-edit"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top">
                            <el-button
                                @click="removeUser(scope.row.id)"
                                type="danger"
                                size="small"
                                icon="el-icon-delete"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="分配角色" placement="top">
                            <el-button 
                            @click="showRoleDialog(scope.row)"
                            type="warning" size="small" icon="el-icon-setting"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryinfo.pagenum"
                :page-sizes="[1, 2, 3, 5]"
                :page-size="queryinfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            ></el-pagination>
        </el-card>
        <!-- dialog 对话框 dialogVisible true显示 false隐藏-->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closeAddDialog">
            <!-- 表单:model="addFrom" 绑定data的数据对象 :rules="addFomrRules" 验证规则-->
            <el-form ref="addFormRef" :model="addFrom" :rules="addFomrRules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addFrom.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addFrom.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addFrom.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addFrom.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑框 -->
        <el-dialog title="修改用户" :visible.sync="EditdialogVisible" width="50%">
            <!-- 编辑表单 :rules 做验证-->
            <el-form ref="form" :model="editForm" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="EditdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">修 改</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="提示" 
        :visible.sync="userdialogVisible" 
        width="50%">
            <div>姓名：{{userinfo.username}}</div>
            <div>角色名称：{{userinfo.role_name}}</div>
            <!-- 角色的下拉框 -->
             <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option
                v-for="item in rolelist"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
                </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button @click="userdialogVisible = false">取 消</el-button>
                <el-button @click="addRole" type="primary">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    //   自定义规则 先在data 里面定义函数
    //  在规则那里 {validator:checkMobile,trigger:"blur"}
    //  验证邮箱
    //  rule,value:文本框的值,callback 失败成功都要 callback()
    var checkEmail = (rule, value, callback) => {
      //  正则表达式 342742@qq.com  leijuncao@itca.cn
      // \w 一个数字字母下划线  \d一个数字  +1个以上 ?0或者1个 *0个以上
      var regEmail = /^\w+@\w+\.\w+$/
      // regEmail.test(值) 匹配成功返回true 失败返回false
      if (!regEmail.test(value)) {
        //不匹配
        return callback(new Error('邮箱格式不正确'))
      }
      return callback() //正确
    }
    //  手机
    var checkMobile = (rule, value, callback) => {
      //  正则表达式 1开头 11位数字 {10} 10个
      // \w 一个数字字母下划线  \d一个数字  +1个以上 ?0或者1个 *0个以上
      var regMobile = /^1\d{10}$/
      // regMobile.test(值) 匹配成功返回true 失败返回false
      if (!regMobile.test(value)) {
        //不匹配
        return callback(new Error('手机格式不正确'))
      }
      return callback() //正确
    }

    return {
      // query: 要搜索的名字
      queryinfo: { query: '', pagenum: 1, pagesize: 2 },
      userlist: [],
      total: 0,
      dialogVisible: false, //隐藏对话框,
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFomrRules: {
        //  名字:对应的规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度3-10位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度3-10位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editForm: {},
      EditdialogVisible: false,
      userdialogVisible: false,//显示分配角色对话框
      userinfo:{},// 当前人的信息
      rolelist:[],//所有角色的数组
      selectedRoleId:'',//选中的角色id
    }
  },
  methods: {
    // 点击确定 获取角色的id 发送ajax 去分配
    async addRole(){
        if(!this.selectedRoleId){//没选
         return this.$message.error('请选择角色')
        }
        // console.log(this.selectedRoleId)
       let {data:res}=await this.$http.put(`users/${this.userinfo.id}/role`,{
            rid:this.selectedRoleId
        })
         if(res.meta.status!=200){
          return this.$message.error('分配角色失败')
         }
         this.$message.success('分配角色成功')
         this.getuserlist();//重新获取数据
         this.userdialogVisible=false
    },
    //显示分配角色对话框对话框 
    async showRoleDialog(userinfo) {
      this.userinfo=userinfo;//赋值当前用户
      //发送ajax 获取 所有角色 放到下拉框里面
      let {data:res}=await this.$http.get("roles")   
      if(res.meta.status!=200){
          return this.$message.error('获取角色列表失败')
      }
      //   成功 赋值rolelist 就循环生成一个select option下拉框
      this.rolelist=res.data;
      this.userdialogVisible = true //显示对话框
    },
    created() {
        this.getuserlist()
    },
    //   点击删除按钮 弹出是否删除框 确定 发送ajax删除用户
    async removeUser(id) {
      // 提示是否删除
      let result = await this.$confirm('是否删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确定 confirm 取消cancel
      if (result !== 'confirm') return this.$message.info('取消删了')
      // 确定了删除 发送ajax 真正去删除
      let { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status != 200) return this.$message.error('删除失败')
      // 成功 重新渲染数据
      this.$message.success('删除成功')
      this.getuserlist()
    },
    async showEditUser(id) {
      // 获取id发送ajax获取当前用户数据 显示到表单
      // console.log(id)// users/:id
      let { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      this.editForm = res.data //正好把数据填上
      //   显示 编辑对话框
      this.EditdialogVisible = true
    },
    async editUser() {
      //去发送ajx 修改用户
      // 预验证
      let { data: res } = await this.$http.put('users/' + this.editForm.id, {
        email: this.editForm.email,
        mobile: this.editForm.mobile
      })
      console.log(res)
      if (res.meta.status != 200) return this.$message.error('修改失败')
      this.$message.success('修改成功')
      // 重新获取数据
      this.getuserlist()
      // 关闭对话框
      this.EditdialogVisible = false
    },
    addUser() {
      // 点击确定按钮 预验证 发送ajax 去添加
      // 预验证
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid);//通过 true 失败false
        if (!valid) return
        // 成功发送ajax去添加用户
        let { data: res } = await this.$http.post('users', this.addFrom)
        console.log(res)
        if (res.meta.status != 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 重新发送ajax 获取用户
        this.getuserlist()
        // 关闭对话框
        this.dialogVisible = false
      })
    },
    closeAddDialog() {
      console.log('关闭了')
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    async getuserlist() {
      // 发送ajax
      // this.$http.get("users",{params:{query:'',pagenum:1,pagesize:2} })
      let { data: res } = await this.$http.get('users', {
        params: this.queryinfo
      })
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('获取失败')
      }
      this.userlist = res.data.users //用户数组
      this.total = res.data.total //总条数
    },
    handleSizeChange(newSize) {
      // 改变 每页的条数
      this.queryinfo.pagesize = newSize //显示的条数 从2条 改成5条
      // 重新发送ajax 获取最新的数据
      this.getuserlist()
    },
    handleCurrentChange(newPage) {
      // 点击改变页码
      this.queryinfo.pagenum = newPage
      // 重新发送ajax 获取对应页码的数据
      this.getuserlist()
    },
    changeSwitch(userinfo) {
      console.log(userinfo)
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
</style>
